package spring.cloud.tasks.tasks_manager.task_item_assign.pick_up.executor;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.common.curator.Curator;
import spring.cloud.tasks.common.task_item_allot.Executor;
import spring.cloud.tasks.common.task_item_allot.TaskItem;
import spring.cloud.tasks.tasks_manager.task_item_assign.PreferExecutorSettings;
import spring.cloud.tasks.tasks_manager.task_item_assign.pick_up.PickUp;

import java.util.Iterator;
import java.util.List;

/**
 * 摘取executor流量，标记该executor的noTraffic为true，并移除其所有任务分片，只摘取所有非本地任务分片，设置totalLoadLevel为0
 */
@Slf4j
@Setter
@Getter
public class PickUpWhenExecutorLostTraffic extends PickUp {

    private String executorId;


    @Override
    protected void log() {
        log.info("Execute the {} with {} extract traffic", this.getClass().getSimpleName(), executorId);
    }

    /**
     * 失去流量但是不下线
     */
    @Override
    public boolean pickUp(Curator curator,//
                          List<String> taskIdList,//
                          List<String> enableTaskIdList,//
                          List<TaskItem> pickUpEdTaskItemList,//
                          List<TaskItem> discardTaskItemList,//
                          List<Executor> onlineExecutorList,//
                          List<Executor> ownTrafficOnlineExecutorList,//
                          PreferExecutorSettings preferExecutorSettings) throws Exception {
        // 摘取该executor的所有任务分片
        Executor targetOnlineExecutor = null;
        Iterator<Executor> iterator = ownTrafficOnlineExecutorList.iterator();
        while (iterator.hasNext()) {
            Executor onlineExecutor = iterator.next();
            if (onlineExecutor.getExecutorId().equals(executorId)) {
                pickUpEdTaskItemList.addAll(onlineExecutor.getTaskItemList());
                onlineExecutor.setNotFlowControl(false);
                onlineExecutor.setTotalLoadLevel(0);
                onlineExecutor.getTaskItemList().clear();
                //
                targetOnlineExecutor = onlineExecutor;
                iterator.remove();
                break;
            }
        }

        if (targetOnlineExecutor == null) {
            log.warn("The executor {} maybe offline, unnecessary to extract traffic", executorId);
            return false;
        } else {
            return true;
        }
        //ownTrafficOnlineExecutorList 失去流量但是不下线
    }

}
